package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exceptionResolver.ExceptionMessage;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    UserService userService;

    @RequestMapping("/getUsername")
    @ExceptionMessage(value = MessageConstant.GET_USERNAME_FAIL)
    public Result getUsername(){
        org.springframework.security.core.userdetails.User user= (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user!=null){
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    @RequestMapping("/add")
    @ExceptionMessage(value = MessageConstant.ADD_USER_FALL)
    public Result add(@RequestBody User user,Integer[] roleIds){
            userService.add(user,roleIds);
            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
    }
    @RequestMapping("/del")
    @ExceptionMessage(value = MessageConstant.DELET_USER_FALL)
    public Result del(Integer id){
            userService.del(id);
            return new Result(true,MessageConstant.DELET_USER_SUCCESS);
    }

    @RequestMapping("/update")
    @ExceptionMessage(value = MessageConstant.EDIT_USER_FALL)
    public Result update(@RequestBody User user,Integer[] roleIds){
            userService.update(user,roleIds);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
    }

    @RequestMapping("/find")
    @ExceptionMessage(value = MessageConstant.GET_USER_FALL)
    public Result find(Integer id){
            User user = userService.find(id);
            return new Result(true,MessageConstant.GET_USER_SUCCESS,user);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.findPage(queryPageBean);
    }
}
